package com.hspedu.generic;

import java.util.*;

/**
 * @Author Stringzhua
 * @Date 2024/3/14 0:03
 * description:举例说明，泛型在HashSet,HashMap的使用情况
 * 练习:
 * 1.创建三个学生对象
 * 2.放入到HashMap中,要求Key是String name,Value是学生对象
 * 3.使用两种方式遍历
 */
public class GenericExercise {
    public static void main(String[] args) {
        //使用泛型给HashSet放入三个学生对象
        //K->String V->Student
        //1.HashSet
        HashSet<Student> students = new HashSet<Student>();
        students.add(new Student("jack", 18));
        students.add(new Student("tom", 28));
        students.add(new Student("marry", 19));
        //使用泛型后,下面的语句就会报错
//        set.add(100);
        for (Student student : students) {
            System.out.println("student = " + student);
        }

//        Iterator<Student> iterator = students.iterator();
//        while (iterator.hasNext()) {
//            Student next = iterator.next();
//            System.out.println("next = " + next);
//        }
        //2.HashMap
        HashMap<String, Student> hm = new HashMap<String, Student>();
//        hm.put("tom","Stringzhua");//error
        /*
        * public class HashMap<K,V> {}
        * */
        hm.put("milan",new Student("milan",18));
        hm.put("smith",new Student("smith",48));
        hm.put("hsp", new Student("hsp", 28));
        //迭代器遍历 EntrySet
        /*
         public Set<Map.Entry<K,V>> entrySet() {
            Set<Map.Entry<K,V>> es;
            return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
        }
        * */
        Set<Map.Entry<String, Student>> entries = hm.entrySet();
        System.out.println("===迭代器遍历===");
        Iterator<Map.Entry<String, Student>> iterator = entries.iterator();
        /*
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        * */
        while (iterator.hasNext()) {
            Map.Entry<String, Student> next =  iterator.next();
            System.out.println(next.getKey()+"-"+next.getValue());
        }
    }
}

class Student {
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
